package base;

import base.intrface.CCommandText;
import base.intrface.CGadget;
import base.intrface.CLineBreak;
import base.intrface.CText;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.util.LinkedList;

public class CWindow {
	public int X;
	public int Y;
	public int Width;
	public int Height;
	public int ViewHeight;
	public LinkedList<CGadget> Gadgets = new LinkedList<CGadget>();
	public LinkedList<CGadget> DisplayingGadgets = new LinkedList<CGadget>();
	public int NextGadgetX, NextGadgetY;
	public boolean PrevSpace = false;
	public int YShift;




	public void Rearrange() {
		DisplayingGadgets.clear();
		Width = CGraphics.GetCanvasWidth() - CGUI.Margins[ 0 ] - CGUI.Margins[ 2 ];
		PrevSpace = false;
		NextGadgetX = 0;
		NextGadgetY = 0;
		for ( CGadget Gadget : Gadgets ) {
			Gadget.Append( this );
		}
		Height = NextGadgetY;
		YShift = Height;
	}



	public void AddText( String Text ) {
		Text += "*";
		String Phrase = "";
		boolean Asterisk = false;
		for ( int N = 0; N < Text.length(); N++ ) {
			if ( Text.charAt( N ) == '*' ) {
				if ( !Phrase.isEmpty() ) {
					CText TextGadget;
					if ( Asterisk ) {
						CCommandText CommandTextGadget = new CCommandText();
						String[] PhraseChunks = Phrase.split( "=" );
						if ( PhraseChunks.length > 1 ) {
							CommandTextGadget.CommandText = PhraseChunks[ 1 ];
							Phrase = PhraseChunks[ 0 ];
						} else {
							CommandTextGadget.CommandText = Phrase;
						}
						TextGadget = CommandTextGadget;
					} else {
						TextGadget = new CText();
					}
					TextGadget.Text = Phrase + " ";
					Gadgets.add( TextGadget );

					Phrase = "";
				}
				Asterisk = !Asterisk;
			} else {
				Phrase += Text.charAt( N );
			}
		}
	}



	public void AddLineBreak() {
		CLineBreak LineBreak = new CLineBreak();
		Gadgets.add( LineBreak );
	}

	
	
	public void Display( Graphics G ) {
		CGraphics.DrawSlider( G, this );
		G.setClip( X, Y, Width, ViewHeight );
		for( CGadget Gadget : DisplayingGadgets ) {
			if( ViewHeight >= Height ) {
				Gadget.Draw( G, X, Y );
			} else {
				Gadget.Draw( G, X, Y + ViewHeight - YShift );
			}
		}
		G.setClip( 0, 0, CGraphics.GetCanvasWidth(), CGraphics.GetCanvasHeight() );
	}
	

	public void Clear() {
		Gadgets.clear();
	}
	
	

	public void CheckScrollBarButtonPress( MouseEvent evt ) {
		if( evt.getX() < X + Width || evt.getX() > X + Width + CGraphics.SliderWidth ) return;
		if( evt.getY() < Y || evt.getY() > Y + ViewHeight ) return;
		CGUI.StartingYShift = YShift;
		CGUI.StartingY = evt.getY();
		CGUI.DraggingSliderWindow = this;
	}
}
